from django.contrib.auth import authenticate, logout
from django.http import JsonResponse
from rest_framework import viewsets, permissions, status
from blogs.models import *
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_simplejwt.tokens import RefreshToken
from users.models import BlogUser
from .serializer import *

from rest_framework.generics import CreateAPIView
from rest_framework.permissions import AllowAny, IsAuthenticated


class BlogArticleViewSet(viewsets.ModelViewSet):
    queryset = BlogArticle.objects.all()
    serializer_class = BlogArticleSerializer
    # 添加访问用户权限限制
    permission_classes = [permissions.IsAuthenticated]

#返回当前登录用户所有博文记录
class BlogArticleByAuthorViewSet(APIView):
    permission_classes = [permissions.IsAuthenticated]
    #查询该用户发布的博文列表
    def get(self, request, *args, **kwargs):
        # 获取当前用户对象
        user = request.user
        # 查询当前用户的博客文章
        blog_articles = BlogArticle.objects.filter(username=user)
        # 序列化查询结果
        serializer = BlogArticleSerializer(blog_articles, many=True)
        return Response(serializer.data, 200)

    #该用户登录后发布博文
    def post(self, request, *args, **kwargs):
        # 获取请求中的数据
        title = request.data.get('title')
        content = request.data.get('content')
        category = request.data.get('category')
        # 创建博客文章
        blog_user = BlogUser.objects.get(username=self.request.user)
        blog_category = BlogCategory.objects.get(name=category)
        try:
            article = BlogArticle.objects.create(
                title=title,
                content=content,
                username=blog_user,
                category=blog_category
            )
            article.save()
            return Response({"code":200,"msg":"created successfully"})
        except:
            return Response({"code":400,"msg":"created failed"})

    # 删除该用户自己发布的指定博文
    def delete(self, request, *args, **kwargs):
        # 获取要删除的博客文章的ID
        article_id = request.data.get('id', None)
        if article_id is None:
            return Response({'detail': '未提供要删除的博客文章的ID。','code':400})
        # 查询博客文章
        try:
            blog_article = BlogArticle.objects.get(id=article_id, username=request.user)
        except BlogArticle.DoesNotExist:
            return Response({'detail': '未找到指定的博客文章。','code':404})
        # 删除博客文章
        blog_article.delete()
        return Response({'detail': '博客文章删除成功。','code':200})

    #部分修改博文内容
    def patch(self,request):
        # 获取请求中的数据
        id = request.data.get('id')
        title = request.data.get('title')
        # 创建博客文章
        blog_user = BlogUser.objects.get(username=self.request.user)
        try:
            article = BlogArticle.objects.get(id=id,username=blog_user)
            article.title=title
            article.save()
            return Response({"code": 200, "msg": "updated successfully"})
        except:
            return Response({"code": 400, "msg": "updated failed"})

#用户注册处理
class RegisterView(APIView):
    permission_classes = [AllowAny]
    authentication_classes = []  # 禁用身份验证
    def post(self,request):
        username = request.data.get('username')
        password = request.data.get('password')
        phone = request.data.get('phone')
        if username and password and phone:
            try:
                user = BlogUser.objects.create_user(username=username, password=password, phone_number=phone)
                return Response({"message": "Register successful.","code":1})
            except Exception as e:
                return Response({'error': str(e),"code":0})
        else:
            return Response({'error': 'Username and password are required',"code":-1})

#处理用户登录
class LoginView(APIView):
    permission_classes = [AllowAny]
    authentication_classes = []  # 禁用身份验证
    def post(self, request):
        try:
            username = request.data.get('username')
            password = request.data.get('password')
            user = authenticate(username=username, password=password)
            if user:
                refresh = RefreshToken.for_user(request.user)
                access_token = str(refresh.access_token)
                return Response({"message": "Login successful.",'code':1,'token':access_token})
        except Exception as e:
            return Response({"message": "Invalid Login.","code":-1})
#处理用户退出
class LogoutView(APIView):
    permission_classes = [AllowAny]
    authentication_classes = []  # 禁用身份验证
    def post(self, request):
        try:
            refresh_token = request.data["token"]
            token = RefreshToken(refresh_token)
            token.blacklist()
            logout(request)
            return Response({"message": "Logout successful.",'code':1})
        except Exception as e:
            return Response({"message": "Invalid refresh token.","code":0})

#对博文点评的管理
class BlogCommentsViewSet(APIView):
    permission_classes = [permissions.IsAuthenticated]

    # 查询该用户登录后查看博文详情时所有的点评列表
    def get(self, request,id, *args, **kwargs):
        # 获取当前用户对象
        user = request.user
        #查询当前id给定的博文对象
        try:
            blog = BlogArticle.objects.get(id=id)
            # 查询该博文所有评论
            blog_commments = BlogComment.objects.filter(blog=blog).order_by('-created_at')
            # 序列化查询结果
            serializer = BlogCommentSerializer(blog_commments, many=True)
            return Response(serializer.data, 200)
        except Exception as e:
            return Response({'error': str(e),'code':400})

    # 该用户登录后针对某篇博文发布点评
    def post(self, request,id, *args, **kwargs):
        # 获取请求中的数据
        blog = request.POST.get('blog')   #博文标题
        content = request.POST.get('comment')  #评论内容
        # 对内容进行过滤审核
        abnormals=["杀人","放火","色情","赌博","反动","诈骗","政府"]
        for word in abnormals:
            if word in content:
            # 如果发现不当言论，返回审核结果和处理建议
                return Response({'status': 'rejected', 'message': '内容包含不当言论，已被拒绝'})
        # 获取关联外键对象
        blog_user = BlogUser.objects.get(username=self.request.user)
        blog_article = BlogArticle.objects.get(title=blog)
        try:
            #保存评论
            comments = BlogComment.objects.create(blog=blog_article,commentor=blog_user,content=content)
            return JsonResponse({'message': 'successfully', 'code': 200})
        except Exception as e:
            return JsonResponse({'error': str(e),'code':400})
